package com.caiden_micheal.base.utils;

import com.caiden_micheal.base.properties.MinioProperties;
import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Component
public class MinioUtil {
    private static final Logger logger = LoggerFactory.getLogger(MinioUtil.class);

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    public Boolean verifySuffix(String suffix) {
        if (!minioProperties.getSuffixList().contains(suffix)) {
            logger.warn("The file format is not supported: " + suffix);
            return false;
        }
        return true;
    }

    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }

    public String upload(String fileName, MultipartFile file) {
        existBucket(minioProperties.getBucketName());
        int index = fileName.lastIndexOf(".");
        String suffix = fileName.substring(index);
        if (!verifySuffix(suffix)) {
            return null;
        }
        String originalName = fileName.substring(0, index);
        if (StringUtils.isEmpty(originalName)) {
            return null;
        }
        fileName = originalName + "_" + System.currentTimeMillis() + suffix;
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).stream(in, in.available(), -1).contentType(file.getContentType()).build());
            return fileName;
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.toString());
                }
            }
        }
    }

    public String removeFile(String fileName) {
        try {
            existBucket(minioProperties.getBucketName());
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
            return fileName;
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
    }
}
